;(function (global) {

    'use strict';

    let skuBuilder = function (params) {
        if (!(this instanceof skuBuilder)) return new skuBuilder(params);
        this.attrList = [];  // 属性列表
        this.formList = [
            {label: '销售价', name: 'skuPrice', placeholder: '请输入'},
            {label: '库存', name: 'skuStock'},
            {label: '商家编码', name: 'skuOuterId'},
            {label: '商品条形码', name: 'skuBarcode'},
        ];

        this.formatData = {id: '', name: 'factorial', node: []}; // 阶乘数据
        this.options = {
            isMergeCell: false,
            mergeImageCell: false,
            class: 'sku-layout-table'
        }
        if (typeof params === 'object') this.options = {...this.options, ...params}
        this.inputList = []
        this.imageList = [];
        this.imageData = [];
        this.formListData = []
    };

    // 设置属性列表
    skuBuilder.prototype.setAttrList = function (attribute) {
        this.attrList = attribute
        this.formatData = this._getFactorial(attribute)
        return this;
    };

    // 获取阶乘数据
    skuBuilder.prototype._getFactorial = function (data, index) {
        let attrCount = data.length;
        if (attrCount < 2 && !index) {
            let node = [];
            for (let i in data[0].node) node.push([data[0].node[i]]);
            return {id: '', name: "sku factorial", node: node};
        }
        if (attrCount < 2) return data[0];

        let idx = 0;
        index = index || 0;
        let arr1 = data[0].node, len1 = arr1.length;
        let arr2 = data[1].node, len2 = arr2.length;
        let aBox = new Array((len1 * len2));
        for (let i = 0; i < len1; i++) {
            for (let j = 0; j < len2; j++) {
                let items = (index === 0) ? new Array(arr1[i]) : arr1[i].slice();
                items.push(arr2[j]);
                aBox[idx] = items;
                idx++;
            }
        }
        let formatData = [];
        formatData.push({id: '', name: "sku factorial", node: aBox});
        for (let i = 2; i < attrCount; i++) formatData.push(data[i]);
        return this._getFactorial(formatData, ++index);
    };

    skuBuilder.prototype.setFormData = function (data) {
        let images = []
        let imageMapper = {}
        data.forEach(item => {
            let salePropKey = this._getPropKey(item.props)
            this.formListData[salePropKey] = item;
            if (item.image && !imageMapper[item.props[0].value]) {
                imageMapper[item.props[0].value] = item.image
                images.push(item.image)
            }
            // if (item.image) images.indexOf(item.image) > -1 || images.push(item.image)
        })

        this.imageData = images
        this._do();
        return this;
    };

    skuBuilder.prototype.getFormData = function () {
        let dataList = []
        let aInputGroup = this._chunk(this.inputList, this.formList.length)
        aInputGroup.forEach((group, key) => {
            let dataItem = {}
            group.forEach((input, index) => {
                dataItem[this.formList[index].name] = input.value
            })
            dataItem.salePropKey = this._getPropKey(this.formatData.node[key])
            dataItem.props = this.formatData.node[key]
            dataList.push(dataItem)
            this.formListData[dataItem.salePropKey] = dataItem
        })
        // 属性
        let ratio = dataList.length / this.imageList.length
        console.log(dataList, 'dataList')
        dataList.forEach((item, index) => {
            item.image = this.imageList[Math.floor(index / ratio)].a
            // item.props[0].image = this.imageList[Math.floor(index / ratio)].a
        })
        return dataList;
    };

    skuBuilder.prototype._getPropKey = function (node) {
        let keyFactor = []
        node.forEach(item => keyFactor.push([item.label].join('_')))
        keyFactor.sort()
        return keyFactor.join(':');
    };


    skuBuilder.prototype.fill = function (key, value) {
        let aInputGroup = this._chunk(this.inputList, this.formList.length)
        let position = this.formList.findIndex(item => item.name === key)
        aInputGroup.forEach(group => group[position].value = value)
        return this;
    };

    skuBuilder.prototype._do = function () {
        let aInputGroup = this._chunk(this.inputList, this.formList.length)
        aInputGroup.forEach((group, key) => {
            let salePropKey = this._getPropKey(this.formatData.node[key])
            if (typeof this.formListData[salePropKey] !== 'undefined') {
                let data = this.formListData[salePropKey]
                group.forEach((input, index) => {
                    input.value = data[this.formList[index].name] || ''
                })
            }
        })
        this.imageList.forEach((item, index) => {
            item.setValue(this.imageData[index] || '')
        })
        return this;
    };

    // 生成表格
    skuBuilder.prototype.build = function (element) {
        this.inputList = []
        this.imageList = []
        let table = document.createElement('table')
        table.className = this.options.class
        table.append(this.createHeader())
        table.append(this.createBody())
        return table
    };


    skuBuilder.prototype.createUploadButton = function () {
        let oDiv = document.createElement('div');
        oDiv.style = 'width:40px;height:40px;border:1px dashed #ccc;font-size:12px;text-align:center;line-height:40px;border-radius: 6px;cursor:pointer;position:relative;flex-direction: column;align-items: center;display:flex;justify-content: center;';
        oDiv.setValue = function (value) {
            let innerHTML = '<div style="width:17px;height: 1px;background-color: #ccc;"></div><div style="width: 1px;height:17px;background-color: #ccc;position: absolute;"></div>';
            if (value) innerHTML = '<img style="max-width: 100%;max-height: 100%;object-fit: cover;width: 100%;height: 100%" src="' + value + '" />';
            this.innerHTML = innerHTML
            this.a = value
        }
        oDiv.setValue('')
        const that = this
        oDiv.addEventListener('click', function () {
            that.options.onUploadClick(function (imgUrl) {
                oDiv.setValue(imgUrl)
            })
        })
        this.imageList.push(oDiv)
        return oDiv
    };

    skuBuilder.prototype.createBody = function () {

        let tbody = document.createElement('tbody')
        let total = this.formatData.node.length
        let merge = total / this.attrList[0].node.length
        this.formatData.node.forEach((nodeList, index) => {
            let tr = document.createElement('tr')
            let rowspan = total

            // 图片
            if (index % merge === 0) {
                let td = document.createElement('td')
                td.setAttribute('rowspan', merge.toString())
                td.append(this.createUploadButton())
                tr.append(td)
            }

            let k = 0;
            for (let j in nodeList) {
                let item = nodeList[j]
                rowspan /= this.attrList[(k++)].node.length;
                if ((index % rowspan) !== 0 && this.options.isMergeCell) continue;
                let td = document.createElement('td')
                td.innerHTML = item.label
                if (item.remark) td.innerHTML += '(' + item.remark + ')'
                if (this.options.isMergeCell) td.setAttribute("rowspan", rowspan.toString());
                tr.append(td)
            }

            this.formList.forEach(item => {
                let td = document.createElement('td');
                let input = document.createElement('input');
                if (item.placeholder) input.setAttribute('placeholder', item.placeholder)
                this.inputList.push(input)
                td.append(input)
                tr.append(td)
            })
            tbody.append(tr)
        })
        return tbody
    };


    skuBuilder.prototype.createHeader = function () {
        let thead = document.createElement('thead');
        let tr = document.createElement('tr');
        let header = ['图片']
        this.attrList.forEach(attr => {
            header.push(attr.name)
        });
        this.formList.forEach(form => {
            header.push(form.label)
        });
        header.forEach(item => {
            let th = document.createElement('th')
            th.innerHTML = item
            tr.append(th)
        })
        thead.append(tr)
        return thead
    };

    // 数组分割多个小数组
    skuBuilder.prototype._chunk = function (array, size) {
        let arr = [];
        for (let i = 0; i < array.length; i = i + size) arr.push(array.slice(i, i + size));
        return arr;
    };


    skuBuilder.prototype.uuid = function () {
        let d = new Date().getTime();
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    };

    global['skuBuilder'] = global['skuBuilder'] || skuBuilder;
})(window);
